<?php

namespace app\common\lib;

use app\common\model\Member;
use app\common\model\MessageTemplate;
use app\common\model\TemplateMessageRecording;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;

class WxTemplateMsg
{
    public static function send($member_id ,$template_id,$params)
    {
        $config = config('wechat_official_account');
        $app = Factory::officialAccount($config);
        $template = MessageTemplate::find($template_id);
        $wx_template_id = trim($template['template_id']);
        $title = $template['name'];
        $content = $template['content'];
        foreach ($params as $key => $value) {
            $content = str_replace('{{' . $key . '.DATA}}', $value, $content);
            //要做截取，否则超过20个字无法发送
            $params[$key]=mb_substr($value,0,20, 'utf-8');
        }
        $member = Member::find($member_id);
            try {
                $result=$app->template_message->send([
                    'touser' => $member['official_openid'],
                    'template_id' => $wx_template_id,
                    'data' => $params
                ]);
                if($result['errcode']==0){
                    TemplateMessageRecording::create([
                        'member_id' => $member_id,
                        'message_template_id' => $template_id,
                        'name' => '发送成功',
                        'content' => $content,
                    ]);
                }else{
                    TemplateMessageRecording::create([
                        'member_id' => $member_id,
                        'message_template_id' => $template_id,
                        'name' => '发送失败,'.$result['errmsg'],
                        'content' => $content,
                    ]);
                }


            } catch (\Exception $e) {
                TemplateMessageRecording::create([
                    'member_id' => $member_id,
                    'message_template_id' => $template_id,
                    'name' => '发送失败,'.$e->getMessage(),
                    'content' => $content,
                ]);
            }
    }


}